"""
用户序列化器
"""
from rest_framework import serializers
from django.contrib.auth import get_user_model
from .models import UserFollow, AdminActionLog

User = get_user_model()


class UserSerializer(serializers.ModelSerializer):
    """用户序列化器"""
    followers_count = serializers.SerializerMethodField()
    following_count = serializers.SerializerMethodField()
    avatar = serializers.SerializerMethodField()
    is_admin = serializers.SerializerMethodField()
    
    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'phone', 'avatar', 'preferences', 'date_joined', 
                  'followers_count', 'following_count', 'is_staff', 'is_superuser', 'is_admin',
                  'email_verified', 'phone_verified')
        read_only_fields = ('id', 'date_joined', 'is_staff', 'is_superuser', 'email_verified', 'phone_verified')
    
    def get_is_admin(self, obj):
        """判断是否为管理员"""
        return obj.is_staff or obj.is_superuser
    
    def get_avatar(self, obj):
        """获取头像URL（完整路径）"""
        if obj.avatar:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.avatar.url)
            return obj.avatar.url
        return None
    
    def get_followers_count(self, obj):
        return obj.followers.count()
    
    def get_following_count(self, obj):
        return obj.following.count()


class UserRegisterSerializer(serializers.ModelSerializer):
    """用户注册序列化器"""
    password = serializers.CharField(write_only=True, min_length=6)
    password_confirm = serializers.CharField(write_only=True, min_length=6)
    
    class Meta:
        model = User
        fields = ('username', 'email', 'phone', 'password', 'password_confirm')
    
    def validate(self, attrs):
        if attrs['password'] != attrs['password_confirm']:
            raise serializers.ValidationError("两次密码输入不一致")
        return attrs
    
    def create(self, validated_data):
        validated_data.pop('password_confirm')
        password = validated_data.pop('password')
        # 使用create_user会自动处理密码加密
        user = User.objects.create_user(
            username=validated_data.get('username'),
            email=validated_data.get('email'),
            phone=validated_data.get('phone', ''),
            password=password
        )
        return user


class UserFollowSerializer(serializers.ModelSerializer):
    """用户关注序列化器"""
    follower_username = serializers.CharField(source='follower.username', read_only=True)
    following_username = serializers.CharField(source='following.username', read_only=True)
    
    class Meta:
        model = UserFollow
        fields = ('id', 'follower', 'following', 'follower_username', 'following_username', 'created_at')
        read_only_fields = ('id', 'created_at')


class AdminActionLogSerializer(serializers.ModelSerializer):
    """管理员操作日志序列化器"""
    admin_username = serializers.CharField(source='admin.username', read_only=True)
    action_display = serializers.CharField(source='get_action_display', read_only=True)
    
    class Meta:
        from .models import AdminActionLog
        model = AdminActionLog
        fields = ('id', 'admin', 'admin_username', 'action', 'action_display', 'target_type', 
                  'target_id', 'target_name', 'description', 'ip_address', 'user_agent', 'created_at')
        read_only_fields = ('id', 'created_at')
